import { QueryKey, useQueryClient } from "react-query";
import { Task } from "types";
import { reorder } from "./reorder";

export const useConfig = (queryKey:QueryKey,callback:(target:any,old?:any[])=>any[]) =>{
  const queryClient = useQueryClient()
  return {
    onSuccess: () => queryClient.invalidateQueries(queryKey),
    async onMutate(target:any) {
      const previousItems = queryClient.getQueryData(queryKey)
      queryClient.setQueryData(queryKey, (old?: any[]) => {
        return callback(target,old)
      })
      return {previousItems}
    },
    onError(error:any,newItem:any,context:any){
      queryClient.setQueryData(queryKey,context.previousItems)
      // queryClient.setQueryData(queryKey,(context as {previousItmes:Project[]}).previousItems)
    }
  }
}

export const useDeleteConfig = (querKey:QueryKey) => 
  useConfig(querKey,(target,old)=> old?.filter(item=>item.id !== target.id) || [])

export const useEditConfig = (querKey:QueryKey) => 
  useConfig(querKey,(target,old)=> old?.map(item=>item.id === target.id ?{...item,...target}:item) || [])

export const useAddConfig = (querKey:QueryKey) => 
  useConfig(querKey,(target,old)=> old? [...old,target]:[] )


export const useReorderKanbanConfig = (queryKey: QueryKey) =>
  useConfig(queryKey, (target, old) => reorder({ list: old, ...target }));

export const useReorderTaskConfig = (queryKey: QueryKey) =>
  useConfig(queryKey, (target, old) => {
    const orderedList = reorder({ list: old, ...target }) as Task[];
    return orderedList.map((item) =>
      item.id === target.fromId
        ? { ...item, kanbanId: target.toKanbanId }
        : item
    );
  });